package com.github.willisaway.core.threadpool;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 线程池封装类，每个类对应一个线程池
 * @author liyougen
 *
 */
@Data
@Slf4j
public class ThreadPool {
    public String code;//线程池代码
    public String name;//线程池名称
    public ThreadPoolExecutor pool = null;
    public Date startTime = new Date(System.currentTimeMillis());//线程池创建时间
    public int nThreads=8;//同时执行的线程数,默认五个,不同业务可设置不同的数量
    /**
     * 构造方法
     */
    public ThreadPool(){
        pool = (ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads);
        startTime = new Date(System.currentTimeMillis());
    }
    
    public ThreadPool(int nThreads){
        this.nThreads = nThreads;
        pool = (ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads);
        startTime = new Date(System.currentTimeMillis());
    }
    
    public void addTask(ThreadExtend thread){
        pool.execute(thread);
    }
    
    public void printPoolInfo(){
        try{
            log.info("----------------------------------------------------------------------------------------------");
            log.info("线程池["+name+"]中等待执行的任务数目："+pool.getQueue().size()+",正在执行的任务数:"+pool.getActiveCount()+",已执行完的任务数目："+pool.getCompletedTaskCount());
//            logger.info("完成进度:"+NumberUtil.decimalFormat2(((double)pool.getCompletedTaskCount()*100)/(pool.getCompletedTaskCount()+pool.getActiveCount()+pool.getQueue().size()))+"%");
            Date curTime = new Date(System.currentTimeMillis());
//            logger.info("线程池已运行:"+NumberUtil.decimalFormat2((((double)curTime.getTime()-startTime.getTime()))/1000/60)+"分钟");
            log.info("----------------------------------------------------------------------------------------------");
        }catch(Exception ex){
            log.error("打印线程池信息出错");
            ex.printStackTrace();
        }
    }
}
